package com.example.rbacmanage.aspect;

import com.example.rbacmanage.annotation.LogAnnotation;
import com.example.rbacmanage.entity.OperLog;
import com.example.rbacmanage.service.OperLogService;
import com.example.rbacmanage.util.AddressUtils;
import com.example.rbacmanage.util.IpUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class LoggingAspect {
    @Autowired
    private OperLogService operLogService;

    @Around("@annotation(com.example.rbacmanage.annotation.LogAnnotation)")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        MethodSignature signature= (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);

        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        System.out.println("The method " + methodName + " elapsed time is " + elapsedTime + " ms.");

        Object[] args = joinPoint.getArgs();
        ObjectMapper objectMapper = new ObjectMapper();
        String params=null;
        if (methodName.equals("importUser") || methodName.equals("exportUser")){
        }else{
            params = objectMapper.writeValueAsString(args[0]);
        }

        OperLog sysLog = new OperLog();
        sysLog.setOperAddr(IpUtils.getIpAddr());
        sysLog.setOperLocation(AddressUtils.getRealAddressByIP(sysLog.getOperAddr()));
        sysLog.setMethodName(methodName);
        sysLog.setClassName(className);
        sysLog.setOperation(logAnnotation.operation());
        sysLog.setModuleName(logAnnotation.module());
        sysLog.setLogDesc(params);
        sysLog.setCreateTime(new Date());
        sysLog.setCreateBy(SecurityContextHolder.getContext().getAuthentication().getName());
        operLogService.save(sysLog);
        return result;
    }
}
